package cn.itcast.demo.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class PaiziFilter extends ZuulFilter {


    /**
     *
     * filter 过滤 的类型
     *
     *
     * 四种  pre,post,routing error
     *
     * type=pre
     *
     * pre--->routing --->post
     *
     * pre---->error--->post
     *
     *
     * pre--->routing ----->error --->post
     *
     *
     * pre--->routing --->post----->error
     *
     *
     * @return
     */

    @Override
    public String filterType() {
        return "pre";
    }


    /**
     *
     * load on start up  相当于
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 决定是否启用这个过滤器
     *
     * true  过滤器生效
     *
     * false 过滤器不生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }


    /**
     *
     * 过滤器，生效后处理的逻辑，是否放行在这里决定了
     *
     * 拦截要单独处理，放行不理会
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        //获取当前请求的 资源管理器
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取request对象
        HttpServletRequest request = currentContext.getRequest();

        String paizi = request.getParameter("paizi");

        //没有符合我的要求，此时拦截，拦截就是不响应
        if (StringUtils.isEmpty(paizi)){

            currentContext.setSendZuulResponse(false);//声明不响应

            currentContext.setResponseStatusCode(401);//未授权

        }

        return null;
    }
}
